<template>
  <view class="report-page">
    <Navbar title="报表生成" />
    <view class="report-content">
      <!-- 区域选择 -->
      <view class="area-select-row">
        <areaFilterVue
          ref="areaFilterRef"
          :filterConfig="filterConfig"
          :areaData="areaStore.areaData"
          @filterChange="handleFilterChange"
        ></areaFilterVue>
      </view>

      <!-- 时间选择 -->
      <view class="time-select-section">
        <view class="time-row">
          <text class="time-label">开始时间</text>
          <view class="time-input" @click="openDatePicker('start')">
            <text class="time-text">{{ startDate || '选择日期' }}</text>
            <image src="/static/img/minePages/calendar-icon.png" mode="widthFix" class="calendar-icon"></image>
          </view>
        </view>
        <view class="time-row">
          <text class="time-label">结束时间</text>
          <view class="time-input" @click="openDatePicker('end')">
            <text class="time-text">{{ endDate || '选择日期' }}</text>
            <image src="/static/img/minePages/calendar-icon.png" mode="widthFix" class="calendar-icon"></image>
          </view>
        </view>
      </view>

      <!-- 数据表格选择 -->
      <view class="table-select-section">
        <text class="section-title">选择数据表格</text>
        <view class="table-type-list">
          <view class="table-type-card" :class="{active: selectedTypes.includes('black')}" @click="selectType('black')">
            <view class="card-header">
              <text class="card-title">黑白名单电器表格</text>
              <view class="checkbox" :class="{checked: selectedTypes.includes('black')}">
                <text v-if="selectedTypes.includes('black')" class="checkmark">✓</text>
              </view>
            </view>
            <text class="card-desc">黑白名单电器的监测记录数据</text>
          </view>
          <view class="table-type-card" :class="{active: selectedTypes.includes('important')}" @click="selectType('important')">
            <view class="card-header">
              <text class="card-title">重点电器表格</text>
              <view class="checkbox" :class="{checked: selectedTypes.includes('important')}">
                <text v-if="selectedTypes.includes('important')" class="checkmark">✓</text>
              </view>
            </view>
            <text class="card-desc">重点电器的使用情况和用电趋势图</text>
          </view>
          <view class="table-type-card" :class="{active: selectedTypes.includes('alarm')}" @click="selectType('alarm')">
            <view class="card-header">
              <text class="card-title">告警记录表格</text>
              <view class="checkbox" :class="{checked: selectedTypes.includes('alarm')}">
                <text v-if="selectedTypes.includes('alarm')" class="checkmark">✓</text>
              </view>
            </view>
            <text class="card-desc">已处理告警事件的详细数据表</text>
          </view>
        </view>
      </view>

      <!-- 日期选择弹窗 -->
      <tn-popup v-model="showDatePicker" open-direction="bottom">
        <tn-calendar
          v-model="tempDate"
          :min-date="tempMinDate"
          :max-date="tempMaxDate"
          @change="onDateConfirm"
          class="detail-calendar"
          active-bg-color="#1ec8e1"
          active-text-color="#fff"
        />
      </tn-popup>
    </view>
    <!-- 导出按钮和说明 -->
    <view class="bottom-actions">
      <view class="export-btn" :class="{disabled: !canExport}" @click="exportReport">导出到本地</view>
      <view class="export-tip">注：导出格式为Excel表格</view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import Navbar from '@/components/Navbar.vue';
import areaFilterVue from '@/components/areaFilter.vue';
import { createRequest } from '@/utils/request';
import { useAreaStore } from '@/store/area';

// 区域数据管理
const areaStore = useAreaStore();

// 区域选择相关
const areaFilterRef = ref(null);

// 筛选配置
const filterConfig = ref({
  maxLevels: 2,
  labels: ['一级区域', '二级区域'],
});

// 当前选中的区域
const selectedArea1 = ref('all');
const selectedArea2 = ref('all');

// 处理筛选变化
const handleFilterChange = (data) => {
  if (data.type === 'filter1') {
    // 一级区域变化
    selectedArea1.value = data.filter1.value || 'all';
    selectedArea2.value = 'all'; // 重置二级区域选择
  } else if (data.type === 'filter2') {
    // 二级区域变化
    selectedArea2.value = data.filter2.value || 'all';
  }
}

// 获取所有区域数据
const fetchAllAreaData = async () => {
  // 区域数据已在登录时获取，无需重复获取
  if (!areaStore.areaDataLoaded) {
    console.warn('区域数据未加载，可能登录时获取失败');
  }
};

// 时间选择相关
const startDate = ref('');
const endDate = ref('');
const selectedTypes = ref([]); // 默认不选中任何报表

// 日历弹窗相关
const showDatePicker = ref(false);
const tempDate = ref('');
const datePickerWhich = ref('start');
const minDate = '2020-01-01';
const maxDate = computed(() => {
  const today = new Date();
  return `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
});

// 动态日期范围限制
const tempMinDate = ref('2020-01-01');
const tempMaxDate = ref('');

// 判断是否可以导出
const canExport = computed(() => {
  return startDate.value && endDate.value && selectedTypes.value.length > 0;
});

// 日期校验函数
const validateDates = () => {
  // 检查是否选择了开始日期
  if (!startDate.value) {
    uni.showToast({ title: '请选择开始日期', icon: 'none' });
    return false;
  }
  
  // 检查是否选择了结束日期
  if (!endDate.value) {
    uni.showToast({ title: '请选择结束日期', icon: 'none' });
    return false;
  }
  
  // 检查开始日期是否早于结束日期
  if (startDate.value >= endDate.value) {
    uni.showToast({ title: '开始日期必须早于结束日期', icon: 'none' });
    return false;
  }
  
  return true;
};

const openDatePicker = (which) => {
  datePickerWhich.value = which;
  tempDate.value = which === 'start' ? startDate.value : endDate.value;
  
  // 动态设置日期范围限制
  if (which === 'start') {
    // 选择开始日期，最大不能超过已选的结束日期
    tempMinDate.value = '2020-01-01';
    tempMaxDate.value = endDate.value || maxDate.value;
  } else {
    // 选择结束日期，最小不能小于已选的开始日期
    tempMinDate.value = startDate.value || '2020-01-01';
    tempMaxDate.value = maxDate.value;
  }
  
  // 确保最小日期不超过最大日期
  if (tempMinDate.value > tempMaxDate.value) {
    uni.showToast({ title: '日期范围不合法', icon: 'none' });
    return;
  }
  
  showDatePicker.value = true;
}

const onDateConfirm = (val) => {
  // 统一日期格式为YYYY-MM-DD
  const dateVal = val.replace(/\//g, '-');
  let min = tempMinDate.value;
  let max = tempMaxDate.value;
  
  // 兜底校验：如果选中日期不在范围内，自动修正并提示
  if (min && dateVal < min) {
    uni.showToast({ title: `日期不能早于${min}`, icon: 'none' });
    // 自动修正为min
    setDateValue(min);
    showDatePicker.value = false;
    return;
  }
  if (max && dateVal > max) {
    uni.showToast({ title: `日期不能晚于${max}`, icon: 'none' });
    // 自动修正为max
    setDateValue(max);
    showDatePicker.value = false;
    return;
  }
  
  setDateValue(dateVal);
  showDatePicker.value = false;
}

// 设置日期值的辅助函数
const setDateValue = (dateVal) => {
  if (datePickerWhich.value === 'start') {
    startDate.value = dateVal;
  } else {
    endDate.value = dateVal;
  }
}

const selectType = (type) => {
  const index = selectedTypes.value.indexOf(type);
  if (index > -1) {
    selectedTypes.value.splice(index, 1);
  } else {
    selectedTypes.value.push(type);
  }
}

const exportReport = async () => {
  // 如果按钮被禁用，直接返回
  if (!canExport.value) {
    return;
  }

  // 进行日期校验
  if (!validateDates()) {
    return;
  }

  console.log('导出报表:', {
    area1: selectedArea1.value,
    area2: selectedArea2.value,
    startDate: startDate.value,
    endDate: endDate.value,
    types: selectedTypes.value
  });
  
  try {
    // 使用createRequest导出Excel
    // const response = await createRequest('/api/export/excel', {
    //   method: 'POST',
    //   data: {
    //     area1: selectedArea1.value,        // 一级区域值
    //     area2: selectedArea2.value,        // 二级区域值
    //     startDate: startDate.value,        // 开始时间
    //     endDate: endDate.value,            // 结束时间
    //     types: selectedTypes.value          // 表格类型数组：['black', 'important', 'alarm']
    //   },
    //   responseType: 'arraybuffer',         // 接收二进制流
    // });

    // 模拟请求成功
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // APP端保存文件
    // const fileSystemManager = uni.getFileSystemManager();
    // const filePath = `${uni.env.USER_DATA_PATH}/报表.xlsx`;
    // fileSystemManager.writeFile({
    //   filePath,
    //   data: response.data,
    //   encoding: 'binary',
    //   success: () => {
    //     uni.openDocument({
    //       filePath,
    //       fileType: 'xlsx',
    //       showMenu: true
    //     });
    //   },
    //   fail: (err) => {
    //     uni.showToast({ title: '保存失败', icon: 'none' });
    //   }
    // });

    uni.showToast({ title: '导出成功', icon: 'success' });
  } catch (error) {
    console.error('导出失败:', error);
    uni.showToast({ title: '导出失败，请重试', icon: 'none' });
  }
}

onLoad(async () => {
  // 获取所有区域数据
  await fetchAllAreaData();
});
</script>

<style scoped lang="scss">
.report-page {
  @include page-with-header;
  background: #172869;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.report-content {
  flex: 1;
  padding: 40rpx 32rpx 0;
}
.area-select-row{
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 70rpx;
  background: rgba(255,255,255,0.15);
  border-radius: 10rpx 10rpx 0 0;
  padding-top: 20rpx;
}

.time-select-section {
  margin-bottom: 40rpx;
  padding: 40rpx 32rpx;
  box-sizing: border-box;
  background: rgba(255,255,255,0.08);
  border-radius: 0 0 10rpx 10rpx;
}

.time-row {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
}

.time-row:last-child {
  margin-bottom: 0;
}

.time-label {
  color: #fff;
  font-size: 28rpx;
  width: 120rpx;
}

.time-input {
  flex: 1;
  height: 56rpx;
  background: rgba(255,255,255,0.08);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20rpx;
  transition: background 0.2s;
  margin-left: 20rpx;
}

.time-input:active {
  background: rgba(30,200,225,0.12);
}

.time-text {
  color: rgba(255,255,255,0.8);
  font-size: 24rpx;
}

.calendar-icon {
  width: 28rpx;
}

.table-select-section {
  margin-bottom: 40rpx;
}

.section-title {
  color: #fff;
  font-size: 32rpx;
  font-weight: 500;
  margin-bottom: 24rpx;
  display: block;
}

.table-type-list {
  display: flex;
  flex-wrap: wrap;
  gap: 24rpx;
}

.table-type-card {
  background: rgba(255,255,255,0.08);
  border-radius: 12rpx;
  width: calc(50% - 12rpx);
  min-width: 260rpx;
  padding: 24rpx;
  box-sizing: border-box;
  border: 2rpx solid transparent;
  transition: all 0.2s;
  cursor: pointer;
}

.table-type-card.active {
  border: 2rpx solid #1ec8e1;
  background: rgba(30,200,225,0.05);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12rpx;
}

.card-title {
  color: #fff;
  font-size: 28rpx;
  font-weight: 500;
}

.checkbox {
  width: 32rpx;
  height: 32rpx;
  border-radius: 6rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
  background-color: rgba(255,255,255,0.3);
}

.checkbox.checked {
  background: rgba(255,255,255,0.1);
}

.checkmark {
  color: #1ec8e1;
  font-size: 20rpx;
  font-weight: bold;
}

.card-desc {
  color: rgba(255,255,255,0.7);
  font-size: 24rpx;
  line-height: 1.4;
}

.bottom-actions {
  width: 100%;
  height: 168rpx;
  background: #071E51;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

.export-btn {
  width: 686rpx;
  height: 80rpx;
  background: linear-gradient(90deg, #3a8dde 0%, #256bda 100%);
  color: #fff;
  font-size: 32rpx;
  border: none;
  border-radius: 40rpx;
  box-shadow: 0 4rpx 16rpx rgba(58, 108, 255, 0.12);
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  
  &:active {
    transform: scale(0.98);
  }
  
  &.disabled {
    background: rgba(255, 255, 255, 0.2);
    color: rgba(255, 255, 255, 0.5);
    box-shadow: none;
    cursor: not-allowed;
    
    &:active {
      transform: none;
    }
  }
}


.export-tip {
  color: rgba(255,255,255,0.5);
  font-size: 24rpx;
  text-align: center;
  margin-top: 16rpx;
}

.detail-calendar {
  box-sizing: border-box;
  color: #eee;
  // 参考consoleView的日期选择器样式
}

:deep(.tn-popup__content) {
  background-color: #1F3462 !important;
}

:deep(.uni-picker-view-mask) {
  background: transparent !important;
}

:deep(.tn-calendar__data) {
  box-sizing: border-box !important;
}

:deep(.tn-calendar__week-text) {
  box-sizing: border-box !important;
}

:deep(.tn-calendar__operation) {
  box-sizing: border-box !important;
}
</style>